package com.imti.retrofitdemo;

import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WeatherPresenter implements IWeatherLogic
{

    @Override
    public void requestCityList(String key, IWeatherPresenter callback)
    {
        List<CityModel> cityModels = new ArrayList<>();

        BaseApplication.weatherRequest.requestCityList(key)
            .flatMap(new Func1<WeatherListResponse<CityResponse>, Observable<CityResponse>>()
            {
                @Override
                public Observable<CityResponse> call(
                    WeatherListResponse<CityResponse> cityResponseWeatherListResponse)
                {
                    return Observable.from(cityResponseWeatherListResponse.getResult());
                }
            })
            .map(cityResponse ->
            {
                CityModel model = new CityModel();
                model.setId(cityResponse.getId());
                model.setCity(cityResponse.getCity());

                return model;
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<CityModel>()
            {
                @Override
                public void onCompleted()
                {
                    callback.onCityListSuccess(cityModels);
                }
                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }
                @Override
                public void onNext(CityModel cityModel)
                {
                    cityModels.add(cityModel);
                }
            });
    }
}

